<template>
  <div id="labItemDict">
    <Breadcrumb content="手工抄录指标" v-if="showBreadCrumbTag === true" />
    <GoBack :content="'手工抄录指标'" v-if="showBreadCrumbTag === false" @closeDrawer="closeDrawer" :backUrl="url"></GoBack>
    <div class="bodyContent">
      <vxe-form :data="searchForm" class="searchform form-input-m">
        <vxe-form-item title="报告单元">
          <template #default>
            <SelectWorkGroupAll ref="selectWorkGroupRef" :url="'/api/rptGroup/findRptGroup'" :inputWidth="'100%'" @fatherMethod="searchWklt" :isShowAll="true" :isClear="true"></SelectWorkGroupAll>
          </template>
        </vxe-form-item>

        <vxe-form-item title="快速查询">
          <vxe-input v-model="searchForm.searchValue" placeholder="请输入" clearable @keyup="keyupEnter" />
        </vxe-form-item>
        <vxe-form-item>
          <el-radio-group v-model="searchForm.enable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </vxe-form-item>
        <vxe-form-item>
          <el-button size="small" type="primary" @click="getReportItemList">查询</el-button>
          <el-button size="small" type="primary" @click="save">保存</el-button>

        </vxe-form-item>
      </vxe-form>
      <div class="tablecenter" :style="{ height: tableBodyHeight }">
        <vxe-table ref="reportTable" class="mytable-scrollbar" border="inner" :scroll-y="{ enabled: true }" resizable show-header-overflow show-overflow height="auto" align="left" :row-config="{ isCurrent: true, isHover: true }" @current-change="rowClick" :data="itemList" :loading="showLoading">
          <vxe-column field="instrClass" title="仪器大类" width="60">
            <template #default="{ row }">
              <span>{{ formatCommon(instrClassDict, row.instrClass) }}</span>
            </template>
          </vxe-column>
          <vxe-column field="rptGroup" title="报告单元" width="150">
            <template #default="{ row }">
              <span>{{ formatReportGroup(reportGroupDict, row.rptGroup) }}</span>
            </template>
          </vxe-column>
          <vxe-column field="itemNo" title="项目代码" width="80"></vxe-column>
          <vxe-column field="itemNa" title="项目名称" min-width="140"></vxe-column>
          <!-- 表头复选框 -->
          <vxe-column type="checkbox" field="isManual" title="是否手工" min-width="140"> </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import GoBack from '@/components/GoBack.vue'; //返回组件
import { ref, reactive, getCurrentInstance, onMounted, computed } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '@/stores/store';
import SelectWorkGroupAll from '../lab_bus/components/SelectWorkGroupAll.vue'; //报告单元默认全部引入下拉组件

import { IsEmpty } from '@/utils/common';
import Template from '@/views/lab_sys/lab_bus/components/Template.vue';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();

let useSize = ref(localStorage.getItem('uiSize') || 'small'); //当前选择的三个尺寸
const tableBodyHeight = computed(() => {
  if (useSize.value === 'default') {
    return 'calc(100% - 106px)';
  } else if (useSize.value === 'large') {
    return 'calc(100% - 114px)';
  } else {
    return 'calc(100% - 104px)';
  }
});

let activeName = ref('infoTab');
const orgList = store.userInfo.orgList;
// 最左侧表单
let searchForm = reactive({
  instrClass: '',
  rptGroup: '',
  searchValue: '',
  enable: 1,
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName
});
let defaultProps = {
  children: 'children',
  label: 'name'
};

const itemClassDict = reactive([]); //项目类型字典
const instrClassDict = reactive([]); //仪器大类字典
const reportGroupDict = reactive([]); //报告单元字典
const itemKindDict = reactive([]); //结果类型字典
let showLoading = ref(false); //表格加载状态
let itemList: any = reactive([]); //表格数据
let sltPurpose: any = ref({});
let sltItemIndex: any = ref();

let showKnowLedgeLoading = ref(false);

let isinit = ref(false); //右侧基本信息 if初始化组件
let form: any = reactive({}); //右侧基本信息表单

let loadingSync = ref(false); //同步数据加载中
let isDisabled = ref(true);
let dictTreeTypeCodes: any = reactive(['reportCategory', 'YQDL', 'LABITEMKIND']);

// 方法定义区 =============
defineExpose({
  init
});

let showBreadCrumbTag = ref(true); //当为true时显示的是普通面包屑 false显示的是返回组件
let url = ref(''); //抽屉要返回的路由地址

function init(row: any, row2: any) {
  url.value = row;
  showBreadCrumbTag.value = !row2;
}

// 关闭抽屉
function closeDrawer() {
  showBreadCrumbTag.value = true; //恢复成面包屑
  proxy.$emit('closeDrawer');
}

onMounted(async () => {
  getDictItemsList(); //批量获取字典 包含了(项目归类/仪器大类)
  getReportGroupDict(); //获取报告单元字典
});

//获取报告单元字典
function getReportGroupDict() {
  reportGroupDict.length = 0;
  const url = '/api/rptGroup/findRptGroup';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      reportGroupDict.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}

//批量获取字典
async function getDictItemsList() {
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  let itemClassType = dictTreeTypeItems.data.find((item) => item.code === 'reportCategory');
  itemClassDict.push(...itemClassType.detailDataList);

  const instrClassType = dictTreeTypeItems.data.find((item) => item.code === 'YQDL');
  instrClassDict.push(...instrClassType.detailDataList);

  const itemKindType = dictTreeTypeItems.data.find((item) => item.code === 'LABITEMKIND');
  itemKindDict.push(...itemKindType.detailDataList);
}

// 表格 项目归类/仪器大类/结果类型 格式化
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

// 表格 报告单元 格式化
function formatReportGroup(arr, value) {
  for (const item of arr) {
    if (item.rptGroup == value) {
      return item.rptGroupName;
    }
  }
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getReportItemList();
  }
}

// 表格点击当前行
const rowClick = ({ row, rowIndex }) => {
  isinit.value = false;
  const $reportTable = proxy.$refs.reportTable;
  if ($reportTable) {
    $reportTable.setCurrentRow(row);

    if (IsEmpty(row.rptGroup)) {
      isDisabled.value = true;
    } else {
      isDisabled.value = false;
    }
    proxy.$nextTick(() => {
      setTimeout(() => {
        $reportTable.scrollToRow(row);
      }, 150);
    });
  }
  Object.assign(form, row);
  //根据ID获取当前报告单元
  sltPurpose.value = row;
  sltItemIndex.value = rowIndex;

  setTimeout(() => {
    isinit.value = true;
  }, 50);
};

function getReportItemList() {
  sltPurpose.value.id = null;
  sltItemIndex.value = 0;
  findLabItemDictList();
}

function save(){
  const selectRows = (proxy.$refs.reportTable as any).getCheckboxRecords();
  const param={
    rptGroup:form.rptGroup,
    dataList:[],
    isNoChange:''
}
  let dataList=[];
  if (selectRows.length>0){
    for (const item of selectRows) {
      const data ={
        rptGroup:item.rptGroup,
        feeCode:item.itemNo
      };
      dataList.push(data)
    }

  }else {
    param.isNoChange='1';
  }
  param.dataList=dataList;

  let url = '/api/qi/feeitemManual/addFeeitemManual';
  proxy.$http
      .post(url, param)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
}

// 获取申请项目列表
function findLabItemDictList() {
  itemList.length = 0;
  showLoading.value = true;
  const url = '/lis/lab/item/findLabItemDictManualList';
  proxy.$http
    .get(url, { params: searchForm })
    .then((res: any) => {
      itemList.length = 0;
      itemList.push(...res.data);
      if (itemList.length > 0) {
        const kn = itemList.find((k) => k.id == sltPurpose.value.id);
        const knindex = itemList.findIndex((k) => k.id == sltPurpose.value.id);
        if (IsEmpty(kn)) {
          rowClick({ row: itemList[0], rowIndex: 0 }); //默认选中第一条数据
        } else {
          rowClick({ row: kn, rowIndex: knindex }); //默认选中第一条数据
        }
        const $xTable1 = proxy.$refs.reportTable as any;

        const checkList = itemList.filter((item) => {
          return item.isManual == 1;
        });

        setTimeout(() => {
          checkList.forEach((item1) => {
            $xTable1.setCheckboxRow(item1, true);
          });
        }, 300);
      }

      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}

function searchWklt(propValue: any) {
  searchForm.rptGroup = propValue.value;
  getReportItemList();
}
</script>
<style lang="scss" scoped>
#labItemDict {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;

      .el-tabs {
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 40px);
          padding: 0 10px;

          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }

    .searchform {
      padding: 10px 0 0 10px;

      :deep(.vxe-form--item) {
        margin-right: 30px;
      }
    }

    .searchform .vxe-input {
      --el-input-width: 120px;
    }

    .searchform .vxe-select {
      --el-select-width: 120px;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
  }
}
</style>
